package com.jmb.api.common.utils;

import com.jmb.api.common.exception.LeaseException;
import com.jmb.api.common.result.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
@Slf4j
public class LoginUserInfo {
    @Autowired
    private RedisUtil redisUtil;

    public Object getUserToken(HttpServletRequest request)   {

        String token = request.getHeader("Token");
        String userId = request.getHeader("UserId");
        if (token == null){
            throw new LeaseException(ResultCodeEnum.TOKEN_NOT_FOUND);
        }
        return redisUtil.get("login:"+userId);
    }
    // 获取用户的真实姓名
    public String getRealName(HttpServletRequest request)   {
        HashMap<String,Object> userToken = (HashMap<String, Object>) getUserToken(request);
        Object username = userToken.get("username");
        if (username == null){
            throw new LeaseException(ResultCodeEnum.WEB_USER_NAME_NOT);
        }
        return username.toString();
    }
    // 获取用户的id
    public Integer getUserId(HttpServletRequest request){
        HashMap<String,Object> userToken = (HashMap<String, Object>) getUserToken(request);
        Object userId = userToken.get("userId");
        if (userId == null){
            throw new LeaseException(ResultCodeEnum.WEB_USER_ID_NOT);
        }
        return userId.hashCode();
    }

}
